package com.androidtestmusicpaly.musicpaly;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.preference.DialogPreference;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class MainActivity extends AppCompatActivity {
    private ImageButton begin;
    private ImageButton stop;
    private ImageButton next;
    private ImageButton last;
    private ListView list;
    private ArrayList<Music> musiclist;

    private TextView textView1;
    private TextView textView2;
    private Handler seekbarhandler;
    private SeekBar seekBar;
    private int duration;
    private int time;

    private int number=0;
    private int status=2;

    private static final int PROGRESS_INCREASE=0;
    private static final int PROGRESS_PAUSE=1;
    private static final int PROGRESS_RESET=2;

    private StatusChangedReceiver receiver;
    private RelativeLayout relativeLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        stop= (ImageButton) findViewById(R.id.imageButton3);
        begin=(ImageButton)findViewById(R.id.imageButton2);
        next=(ImageButton)findViewById(R.id.imageButton4);
        last=(ImageButton)findViewById(R.id.imageButton1);
        list=(ListView)findViewById(R.id.listView1);
        textView1=(TextView)findViewById(R.id.text1);
        textView2=(TextView)findViewById(R.id.text2);
        seekBar=(SeekBar)findViewById(R.id.seekBar);
        relativeLayout=(RelativeLayout)findViewById(R.id.relativelayout1);
        setListeners();
        initMusiclist();
        listview();
        checkmusic();
        duration=0;
        time=0;
        bindStaatusChingedRecevier();
        initSeekBarHandler();
        startService(new Intent(this,MusicService.class));
        status=MusicService.COMMAND_STOP;
    }
    private void bindStaatusChingedRecevier(){
        receiver=new StatusChangedReceiver();
        IntentFilter filter=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver,filter);
    }
    protected void onResume(){
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean propetry = new PropertyBean(MainActivity.this);
        String theme = propetry.getTheme();
        //设置activity的主题
        setTheme(theme);
    }
    private void setListeners(){
        begin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    default:
                        break;
                }

            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
            }
        });
        last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                number=i;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
               if(status==MusicService.STATUS_PLAYING){
                    time=i;
                    textView1.setText(formatTime(time));
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if(status!=MusicService.STATUS_STOPPED){
                    time=seekBar.getProgress();
                    textView1.setText(formatTime(time));
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                  //  seekbarhandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
                if(status==MusicService.STATUS_PLAYING){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    seekbarhandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
                if(status==MusicService.STATUS_PAUSED){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekbarhandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekbarhandler.sendEmptyMessage(PROGRESS_PAUSE);

            }
        });
    }
    private void initMusiclist(){
        musiclist = Musiclist.getMusiclist();
        //避免重复添加音乐
        if(musiclist.isEmpty())
        {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载到ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>"))
                    strArtist = "无艺术家";
                Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                musiclist.add(music);
            }
        }
    }
    private void listview(){
        List<Map<String,String>> listmap=new ArrayList<Map<String,String>>();
        HashMap<String,String> map;
        SimpleAdapter simpleAdapter;
        for(Music music:musiclist){
            map=new HashMap<String, String>();
            map.put("musicName",music.getMusicName());
            map.put("musicArtist",music.getMusicArtist());
            listmap.add(map);
        }
        String[] from=new String[]{"musicName","musicArtist"};
        int[] to={R.id.listview_tv_title_item,R.id.listview_tv_artist_item};
        simpleAdapter=new SimpleAdapter(this,listmap,R.layout.listview,from,to);
        list.setAdapter(simpleAdapter);
    }
    private void checkmusic(){
        if(musiclist.isEmpty()){
            next.setEnabled(false);
            begin.setEnabled(false);
            last.setEnabled(false);
            stop.setEnabled(false);
            Toast.makeText(getApplicationContext(),"当前没有歌曲",Toast.LENGTH_LONG).show();
        }else{
            next.setEnabled(true);
            begin.setEnabled(true);
            last.setEnabled(true);
            stop.setEnabled(true);
        }
    }
    private void sendBroadcastOnCommand(int command){
        Intent intent=new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command",command);
        switch (command){
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number",number);break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                    break;
        }
        sendBroadcast(intent);
    }

   class StatusChangedReceiver extends BroadcastReceiver{

       @Override
       public void onReceive(Context context, Intent intent) {
           status=intent.getIntExtra("status",-1);
           switch (status){
               case MusicService.STATUS_PLAYING:
                   seekbarhandler.removeMessages(PROGRESS_INCREASE);
                   time=intent.getIntExtra("time",0);
                   duration=intent.getIntExtra("duration",0);
                   number=intent.getIntExtra("number",number);
                   list.setSelection(number);
                   seekBar.setProgress(time);
                   seekBar.setMax(duration);
                   seekbarhandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                   textView2.setText(formatTime(duration));
                   begin.setBackgroundResource(R.drawable.pause);
                   break;
               case MusicService.STATUS_PAUSED:
                   seekbarhandler.sendEmptyMessage(PROGRESS_PAUSE);
                   begin.setBackgroundResource(R.drawable.play);
                   break;

               case MusicService.STATUS_STOPPED:
                   time=0;
                   duration=0;
                   textView1.setText(formatTime(time));
                   textView2.setText(formatTime(duration));
                   seekbarhandler.sendEmptyMessage(PROGRESS_RESET);

                   begin.setBackgroundResource(R.drawable.play);
                   break;
               case MusicService.STATUS_COMPLETED:
                   number=intent.getIntExtra("number",0);
                   if(number==Musiclist.getMusiclist().size()-1){
                       sendBroadcastOnCommand(MusicService.COMMAND_STOP);
                   }else {
                       sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                   }
                   seekbarhandler.sendEmptyMessage(PROGRESS_RESET);
                   begin.setBackgroundResource(R.drawable.play);
                   break;
               default:
                   break;
           }
       }
   }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }
    private String formatTime(int mesc){
        int minute=mesc/1000/60;
        int second=mesc/1000%60;
        String minutestring;
        String secondstring;
        if(minute<10){
            minutestring="0"+minute;
        }else {
            minutestring=""+minute;
        }
        if(second<10){
            secondstring="0"+second;
        }else {
            secondstring=""+second;
        }
        return minutestring+":"+secondstring;
    }

    private void setTheme(String theme){
        if(theme.equals("彩色")){
            relativeLayout.setBackgroundResource(R.drawable.bg_color);
        }else if(theme.equals("花朵")){
            relativeLayout.setBackgroundResource(R.drawable.bg_digit_flower);
        }else if(theme.equals("群山")) {
            relativeLayout.setBackgroundResource(R.drawable.bg_mountain);
        }else if(theme.equals("小狗")){
            relativeLayout.setBackgroundResource(R.drawable.bg_running_dog);
        }else if(theme.equals("冰雪")) {
            relativeLayout.setBackgroundResource(R.drawable.bg_snow);
        }else if(theme.equals("女孩")){
            relativeLayout.setBackgroundResource(R.drawable.bg_music_girl);
        }else if(theme.equals("朦胧")) {
            relativeLayout.setBackgroundResource(R.drawable.bg_blur);
        }
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case R.id.menu_theme:
                new AlertDialog.Builder(this).setTitle("请选择主题").setItems(R.array.theme, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String theme = PropertyBean.THEMES[i];
                        MainActivity.this.setTheme(theme);
                        PropertyBean property = new PropertyBean(MainActivity.this);
                        property.setAndSaveTheme(theme);
                    }
                }).show();
                break;
            case R.id.about:
                new AlertDialog.Builder(MainActivity.this).setTitle("GracePlay").setMessage(R.string.about2).show();
                break;
            case R.id.quit:
                new AlertDialog.Builder(MainActivity.this).setTitle("提示").setMessage(R.string.quit_message)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                System.exit(0);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    private void initSeekBarHandler() {
        seekbarhandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekbarhandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            textView1.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekbarhandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekbarhandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        textView2.setText("00:00");
                        break;
                }
            }
        };
    }
}
